package it.sciuto.greetings.activities;

import it.sciuto.greetings.R;
import it.sciuto.greetings.adapters.BackgroundAdapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class BackgroundDialogActivity extends ListActivity {
	private LinkedList<Bitmap> backgrounds;
	private String[] assetsURL;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getListView().setBackgroundResource(R.drawable.back);

		// Fade Animation
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);

		initBackgrounds();
		setListAdapter(new BackgroundAdapter(this, backgrounds));
		getListView().setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Intent data = new Intent();
				data.putExtra("URL", "url");
				setResult(RESULT_OK, data);
				finish();
			}
		});
	}

	/**
	 * 
	 */
	private void initBackgrounds() {
		backgrounds = new LinkedList<Bitmap>();
		try {
			assetsURL = getAssets().list("easter");
			for (String url : assetsURL) {
				backgrounds.add(getBitmapFromAsset(url));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param url
	 * @return
	 */
	private Bitmap getBitmapFromAsset(String url) {
		InputStream is = null;
		try {
			is = this.getResources().getAssets().open("easter/" + url);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return BitmapFactory.decodeStream(is);

	}

}
